/**通用JavaScript**/
// 通用加载
var load_index;
// 显示加载
function show_loading() {
	load_index = layer.load(1);
}
// 关闭加载
function close_loading() {
	if (load_index != undefined) {
		layer.close(load_index);
	}
}

/**
 * 判断对象是否是数组
 * @author 段文杰
 * @date   2017-07-26
 * @param  object [被判断对象]
 * @return true/false
 */
function isArray(object) {
	return object && typeof object === 'object' && Array == object.constructor;
}

/*弹出层*/
/*
	参数解释：
	title	标题
	url		请求的url
	id		需要操作的数据id
	w		弹出层宽度（缺省调默认值）
	h		弹出层高度（缺省调默认值）
*/
function layer_show(title, url, w, h, full) {
	if (title == null || title == '') {
		title = false;
	}
	if (url == null || url == '') {
		url = "404.html";
	}
	if (w == null || w == '') {
		w = 800;
	}
	if (h == null || h == '' || h > $(window).height() - 30) {
		h = ($(window).height() - 30);
	}
	var page = layer.open({
		type: 2,
		area: [w + 'px', h + 'px'],
		fix: false, //不固定
		maxmin: true,
		shade: 0.4,
		title: title,
		content: url,
		closeBtn: 0
	});
	if (typeof(full) != "undefined" && full != null && full) {
		layer.full(page);
	}
}
/*关闭弹出框口*/
function layer_close() {
	var index = parent.layer.getFrameIndex(window.name);
	parent.layer.close(index);
}
// 弹出页面关闭按钮事件
$('.dialog-page .close-btn').click(function(event) {
	layer_close();
});

// 验证表单
$('#validate-form').validate();

// 模态对话框提交事件
$('.dialog-page .submit-btn').click(function(event) {
	event.preventDefault();
	if ($('#validate-form').valid()) {
		$.ajax({
				url: $('#validate-form').attr('action'),
				type: 'POST',
				dataType: 'json',
				data: $('#validate-form').serialize(),
				beforeSend: function(xhr) {
					show_loading();
				}
			})
			.always(function() {
				close_loading();
			})
			.fail(function(jqXHR, textStatus, errorThrown) {
				layer.msg('操作失败，错误代码：' + textStatus);
			})
			.done(function(data, textStatus, jqXHR) {
				console.log(data);
				if (data.status == 0) {
					layer.msg(data.msg, {
						time: 1000
					}, function() {
						parent.location.reload();
					});
				} else {
                    var message = data.msg;
                    if(message.indexOf("|") >= 0){
						//说明有多个提示
                        var msg = '';
                        var msgArr = message.split('|');
                        for(var i=0;i<msgArr.length;i++){
                            msg += msgArr[i] + '<br />';
						}
                        layer.msg(msg, {
                            icon: 5,
                            shift: 6
                        });
					}else{
                        layer.msg(message, {
                            icon: 5,
                            shift: 6
                        });
					}
				}
			});
	}
});

// 单页面提交事件
$('.single-page .submit-btn').click(function(event) {
	event.preventDefault();
	if ($('#validate-form').valid()) {
		$.ajax({
				url: $('#validate-form').attr('action'),
				type: 'POST',
				dataType: 'json',
				data: $('#validate-form').serialize(),
				beforeSend: function(xhr) {
					show_loading();
				}
			})
			.always(function() {
				close_loading();
			})
			.fail(function(jqXHR, textStatus, errorThrown) {
				layer.msg('操作失败，错误代码：' + textStatus);
			})
			.done(function(data, textStatus, jqXHR) {
				if (data.status == 0) {
					layer.msg(data.msg, {
						time: 1000
					});
				} else {
                    var message = data.msg;
                    if(message.indexOf("|") >= 0){
                        //说明有多个提示
                        var msg = '';
                        var msgArr = message.split('|');
                        for(var i=0;i<msgArr.length;i++){
                            msg += msgArr[i] + '<br />';
                        }
                        layer.msg(msg, {
                            icon: 5,
                            shift: 6
                        });
                    }else{
                        layer.msg(message, {
                            icon: 5,
                            shift: 6
                        });
                    }
				}
			});
	}
});

// 验证label点击事件
$('#validate-form').on('click', 'label.error', function(event) {
	event.preventDefault();
	$(this).remove();
});

$('.layui-table').on('click', '.delete-btn', function(event) {
	event.preventDefault();
	// url
	var url = $(this).attr('href');
	// 对话框内容
	var content = $(this).attr('data-content') ? $(this).attr('data-content') : "确认要删除吗？";
	// 父页面删除模式
	var is_parent = $(this).attr('data-parent') ? $(this).attr('data-parent') : false;
	// 等待加载遮罩层序号
	var load_index;
	var newLayer = is_parent ? parent.layer : layer;
	newLayer.confirm(content, {
		icon: 3
	}, function(index) {
		if (url && url != '') {
			$.ajax({
					url: url,
					type: 'GET',
					dataType: 'json',
					beforeSend: function(xhr) {
						show_loading();
					}
				})
				.always(function() {
					close_loading();
				})
				.fail(function(jqXHR, textStatus, errorThrown) {
					newLayer.msg('操作失败，错误代码：' + textStatus);
				})
				.done(function(data, textStatus, jqXHR) {
					if (data.status == 0) {
						newLayer.msg(data.msg, {
							time: 1000
						}, function() {
							if (is_parent) {
								parent.location.reload();
							} else {
								self.location.reload();
							}
						});
					} else {
                        var message = trim(data.msg);
                        if(message.indexOf("|") >= 0){
                            //说明有多个提示
                            var msg = '';
                            var msgArr = message.split('|');
                            for(var i=0;i<msgArr.length;i++){
                                msg += msgArr[i] + '<br />';
                            }
                            layer.msg(msg, {
                                icon: 5,
                                shift: 6
                            });
                        }else{
                            layer.msg(message, {
                                icon: 5,
                                shift: 6
                            });
                        }
					}
				});
		} else {
			newLayer.msg('URL错误!', {
				icon: 2,
				time: 1000
			});
		}
	});
});
$('.layui-table').on('click', '.passed-btn', function(event) {
	event.preventDefault();
	// url
	var url = $(this).attr('href');
	// 对话框内容
	var content = $(this).attr('data-content') ? $(this).attr('data-content') : "确认要审核吗？";
	// 父页面删除模式
	var is_parent = $(this).attr('data-parent') ? $(this).attr('data-parent') : false;
	// 等待加载遮罩层序号
	var load_index;
	var newLayer = is_parent ? parent.layer : layer;
	newLayer.confirm(content, {
		icon: 3
	}, function(index) {
		if (url && url != '') {
			$.ajax({
					url: url,
					type: 'GET',
					dataType: 'json',
					beforeSend: function(xhr) {
						show_loading();
					}
				})
				.always(function() {
					close_loading();
				})
				.fail(function(jqXHR, textStatus, errorThrown) {
					newLayer.msg('操作失败，错误代码：' + textStatus);
				})
				.done(function(data, textStatus, jqXHR) {
					if (data.status == 0) {
						newLayer.msg(data.msg, {
							time: 1000
						}, function() {
							if (is_parent) {
								parent.location.reload();
							} else {
								self.location.reload();
							}
						});
					} else {
						newLayer.msg(data.msg, {
							time: 2000
						});
					}
				});
		} else {
			newLayer.msg('URL错误!', {
				icon: 2,
				time: 1000
			});
		}
	});
});
// 自动添加必须输入项目的红色点状标志
$('#validate-form').find('.layui-form-item').each(function(index, el) {
	$this = $(this);
	$this.find('[required]').each(function(index, el) {
		var prev_el = $(this).parent().prev();
		if (prev_el.hasClass('layui-form-label') && prev_el.find('.lable-must').length == 0) {
			prev_el.prepend('<span class="lable-must"></span>');
		}
	});
});

// 必须输入红色标志提示tips
$('body').on('mouseenter', '.lable-must', function(event) {
	event.preventDefault();
	layer.tips('必须输入', this, {
		tips: [1, '#FF5722'],
		time: 2000
	});
});
// 条件必须输入黄色提示tips
$('body').on('mouseenter', '.lable-condition-must', function(event) {
	event.preventDefault();
	var msg = $(this).data('msg') ? $(this).data('msg') : '一定条件下必须输入';
	layer.tips(msg, this, {
		tips: [1, '#FFB800'],
		time: 3000
	});
});

// 修正Select组件构建完成缺少必须选择验证的问题
function fixSelectValidate() {
	$('#validate-form .layui-form-item').find('select').each(function(index, el) {
		if ($(this).prop('required')) {
			var select_warp = $(this).siblings('.layui-form-select');
			if (select_warp) {
				select_warp.find('input').prop('required', 'true').attr('name', $(this).attr('name') + '_select');
			}
		}
	});
	layui.form.on('select', function(data) {
		if (data.value != "") {
			$(this).parent("dl").siblings(".layui-select-title").children("label").css("display", "none");
			$(this).parent("dl").siblings(".layui-select-title").children("input").removeClass("error")
		}
	});
}
//封装网络请求
function ps_ajax(url, data, type, dataType, successfn, errorfn, loadingTips) {
	var loading;
	var loadingTips = arguments[6] ? arguments[6] :1;//1:启用，2：禁用
	$.ajax({
		type: type,
		data: data,
		url: url,
		dataType: dataType,
		beforeSend: function(xhr) {
			if(loadingTips  == 1){
				loading = layer.msg('处理数据中······', {
					icon: 16,
					time: 0
				});
			}
		},
		success: function(d) {
			//验证结果
			successfn(d);
			if(loadingTips  == 1) layer.close(loading);
		},
		error: function(e) {
			errorfn(e);
			if(loadingTips  == 1) layer.close(loading);
		}
	});
}
//显示系统返回的错误信息
function show_error_msg(data){
    var message = trim(data.msg);
    if(message.indexOf("|") >= 0){
        //说明有多个提示
        var msg = '';
        var msgArr = message.split('|');
        for(var i=0;i<msgArr.length;i++){
            msg += msgArr[i] + '<br />';
        }
        layer.msg(msg, {
            icon: 5,
            shift: 6
        });
    }else{
        layer.msg(message, {
            icon: 5,
            shift: 6
        });
    }
}
fixSelectValidate();

// tips帮助按钮
$('.tips-help-btn').click(function(event) {
	if ($('.tips-help-content')) {
		layer.open({
			title: '帮助信息',
			type: 1,
			skin: 'layui-layer-rim', //加上边框
			area: ['50%', '70%'], //宽高
			content: $('.tips-help-content').html()
		});
	}
});

//获取url中的参数
function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}

//设置url中参数值
function setUrlParam(name, value) {
	var query = location.search.substring(1);
	var firstUrl = location.href.split('?')[0];
	var p = new RegExp("(^|)" + name + "=([^&]*)(|$)");
	if (p.test(query)) {
		var firstParam = query.split(name)[0];
		var secondParam = query.split(name)[1];
		if (secondParam.indexOf("&") > -1) {
			var lastPraam = secondParam.split("&")[1];
			return firstUrl + '?' + firstParam + '&' + name + '=' + value + '&' + lastPraam;
		} else {
			if (firstParam) {
				return firstUrl + '?' + firstParam + '&' + name + '=' + value;
			} else {
				return firstUrl + '?' + name + '=' + value;
			}
		}
	} else {
		if (query == '') {
			return firstUrl + '?' + name + '=' + value;
		} else {
			return firstUrl + '?' + query + '&' + name + '=' + value;
		}
	}
}
// 切换每页显示记录数
$('.table-page .page-row-num').change(function(event) {
	var url = setUrlParam('pageNum', '1&pageSize='+$(this).val());
	window.location.href = url;
});
// 分页跳转
function pageLink(currentPage){
    location.href= setUrlParam("pageNum", currentPage);
}
function flushIframe(obj){
	var parentFrameId = obj.frameElement.getAttribute('parentFrameId');
	var frame = obj.parent.document.getElementById(parentFrameId);
	if(frame) {
		var subFrame = frame.contentWindow.document.getElementById("page_frame");
		subFrame.setAttribute('src', subFrame.getAttribute('src'));
	}
}
function getChar(index, str) {
    if(!str) {
        str = '';
    }
    var intVal = parseInt((index) / 26);
    if(intVal > 0) {
        str = getChar(intVal - 1 );
        var remainder = (index) % 26;
        return str + getChar(remainder, str);
    } else {
        return String.fromCharCode(64 + parseInt(index + 1));
    }
}

function trim(str){

    return str.replace(/(^\s*)|(\s*$)/g, "");

}
